package com.letfox.ad.service.impl;


import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;










import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.letfox.ad.model.ADAppProduct;
import com.letfox.ad.model.ADPlan;
import com.letfox.ad.model.ADServingMaterial;
import com.letfox.ad.model.OSSConstant;
import com.letfox.ad.model.relation.ADPlanMater;
import com.letfox.ad.service.ADAppService;
import com.letfox.ad.service.ADPlanService;
import com.letfox.ad.service.ADServingMaterialService;
import com.letfox.ad.service.AdAppServService;
import com.letfox.ad.service.relation.ADPlanMaterService;
import com.letfox.ad.util.ADUtil;
import com.letfox.ad.util.OSSUtil;
import com.letfox.common.enums.ResponseEnum;
import com.letfox.common.model.ResultResponse;
@Service
public class AdAppServServiceImpl implements AdAppServService {
	
	@Autowired
	private ADServingMaterialService adServingMaterialService;
	@Autowired
	private ADPlanService adPlanService;
	@Autowired
	private ADPlanMaterService adPlanMaterService;
	@Autowired
	private ADAppService adAppService;
	
	@Override
	@Transactional(rollbackFor = Exception.class) 
	public ResultResponse adAppCreate(ADAppProduct ADAppProduct) throws Exception{
		ResultResponse resultResponse=new ResultResponse();
		OSSClient ossClient=null;
		String fileName=null;
		String url=null;
		List<String> objectList=null;
		//时间格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//转换创建产品JSON数据
		net.sf.json.JSONObject jsonParent = net.sf.json.JSONObject.fromObject(ADAppProduct.getAdParent());
		//转换广告定向设置
		net.sf.json.JSONObject jsonAllocate = net.sf.json.JSONObject.fromObject(ADAppProduct.getAllocateParent());
		//广告表
		ADPlan adPlan=new ADPlan();
		adPlan.setAdPlanId(UUID.randomUUID().toString());
		adPlan.setAdPlanName(jsonParent.getString("plan_name"));
		adPlan.setStartTime(sdf.parse(jsonParent.getString("start_date")));
		adPlan.setEndTime(sdf.parse(jsonParent.getString("end_date")));
		adPlan.setAdType(jsonAllocate.getString("ollocateType"));
		adPlan.setTargetUrl(jsonParent.getString("webSiteAdUrl")==""?null:jsonParent.getString("webSiteAdUrl"));
		adPlan.setAdPlanBudgetDaily(new BigDecimal(jsonAllocate.getString("alloateLimit")==""?null:jsonAllocate.getString("alloateLimit")));
		adPlan.setCreateTime(new Date());
		adPlan.setUpdateTime(new Date());
		adPlan.setCreateBy("system");
		adPlan.setUpdateBy("system");
		adPlan.setDel("0");
		//添加数据库
		adPlanService.insert(adPlan);
		//广告素材表
		ADServingMaterial adServingMaterial=new ADServingMaterial();
		adServingMaterial.setCreateBy("system");
		adServingMaterial.setUpdateBy("system");
		adServingMaterial.setDel("0");
		//广告标题图片
		MultipartFile titleFile=ADAppProduct.getTitleFile();
		//弹窗素材
		MultipartFile adPopUpFile=ADAppProduct.getAdPopUp();
		//全屏素材
		MultipartFile adFullScreen=ADAppProduct.getAdFullScreen();
		//将素材封装入数组中
		MultipartFile[] multipartFiles={titleFile,adPopUpFile,adFullScreen};	
		try {
			ossClient=OSSUtil.getInstance();
			for (int i = 0; i < 3; i++) {
				MultipartFile multipartFile=multipartFiles[i];
				objectList=new ArrayList<String>();
				if (multipartFile!=null) {			
					//素材重命名
					fileName=ADUtil.getRandomFileName(multipartFile.getOriginalFilename());
					//将广告素材上传至阿里云OSS
					OSSUtil.ossUpload(ossClient, multipartFile.getInputStream(), fileName);
					//设置访问权限
					OSSUtil.ossFileACL(ossClient, OSSConstant.IMAGES+fileName, OSSConstant.PUBLIC_READ);
					objectList.add(OSSConstant.IMAGES+fileName);
					//返回URL
					url=OSSConstant.OSSHTTPS+fileName;
					BufferedImage image = ImageIO.read(multipartFile.getInputStream());
					adServingMaterial.setAdMaterialId(UUID.randomUUID().toString());
					adServingMaterial.setAdMaterialType(i+"");
					adServingMaterial.setAdMaterialName(multipartFile.getOriginalFilename());
					adServingMaterial.setAdMaterialUrl(url);
					adServingMaterial.setHeight(image.getHeight());
					adServingMaterial.setWidth(image.getWidth());
					adServingMaterial.setCreateTime(new Date());
					adServingMaterial.setUpdateTime(new Date());
					//存入数据库
					adServingMaterialService.insert(adServingMaterial);
					//关联关系表
					ADPlanMater adPlanMater=new ADPlanMater();
					adPlanMater.setAdMaterId(adServingMaterial.getAdMaterialId());
					adPlanMater.setAdPlanId(adPlan.getAdPlanId());
					adPlanMater.setCreateTime(new Date());
					adPlanMater.setUpdateTime(new Date());
					adPlanMater.setCreateBy("system");
					adPlanMater.setUpdateBy("system");
					adPlanMater.setDel("0");
					//添加数据关联
					adPlanMaterService.insert(adPlanMater);
				}
			}
		} catch (Exception e) {
			if (objectList!=null) {
				//删除图片
				OSSUtil.ossDelete(ossClient, objectList);
			}
			//关闭OSS连接池
		    ossClient.shutdown();
			throw new Exception(e);	
		}
		String response_json="{\"ret_code\": \"ret_code\",\"ret_code\": \"保存成功\"}";
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());	
		resultResponse.setData(response_json);
		//关闭OSS连接池
	    ossClient.shutdown();
		return resultResponse;
	}

	@Override
	public ResultResponse adTotalCensus(String request_json) throws Exception {
		JSONObject jsonObject = JSON.parseObject(request_json);
		ResultResponse resultResponse=new ResultResponse();
		Map<String, String> map=new HashMap<String, String>();
		map.put("group_id", jsonObject.getString("group_id"));
		map.put("start_date", jsonObject.getString("start_date"));
		map.put("end_date", jsonObject.getString("end_date"));
		Map<String, String> totalMap=new HashMap<String, String>();
		try {
			//查询上报汇总数据
			totalMap=adAppService.adTotalCensus(map);
		} catch (Exception e) {
			throw new Exception("sql erro",e);	
		}
		double click_times=Integer.parseInt(String.valueOf(totalMap.get("click_times")));
		double imp_times=Integer.parseInt(String.valueOf(totalMap.get("imp_times")));
		double conver_times=Integer.parseInt(String.valueOf(totalMap.get("conver_times")));
		NumberFormat nt = NumberFormat.getPercentInstance(); 
		nt.setMinimumFractionDigits(2); 
		String click_rate=nt.format(click_times/imp_times);
		String conver_rate=nt.format(conver_times/imp_times);
		totalMap.put("click_rate", click_rate);
		totalMap.put("conver_rate", conver_rate);
		resultResponse.setData(JSON.toJSONString(totalMap));
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}

	@Override
	public ResultResponse adCensusList(String request_json) throws Exception {
		JSONObject jsonObject = JSON.parseObject(request_json);
		ResultResponse resultResponse=new ResultResponse();
		Map<String, String> map=new HashMap<String, String>();
		String reportType=jsonObject.getString("select_type");
		map.put("group_id", jsonObject.getString("group_id"));
		map.put("reportType", reportType);
		map.put("start_date", jsonObject.getString("start_date"));
		map.put("end_date", jsonObject.getString("end_date"));
		Map<String, String> censusMap=new HashMap<String, String>();
		List<Map<String, String>> census_list=new ArrayList<Map<String,String>>();
		try {
			if (reportType.equals("4")) {
				censusMap=adAppService.queryAmountByDate(map);
			}else {
				censusMap=adAppService.queryCensusByDate(map);
			}
		} catch (Exception e) {
			throw new Exception("sql erro",e);	
		}
		census_list.add(censusMap);
		resultResponse.setData(JSON.toJSONString(census_list));
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}
}
